"""
用于处理Markdown文本分块的工具函数
"""
from typing import Dict, List, Optional

def get_heading_level(line: str) -> int:
    """获取标题的层级
    
    Args:
        line: 文本行
        
    Returns:
        int: 标题层级(1-6),非标题返回0
    """
    if not line.strip().startswith('#'):
        return 0
    return len(line.strip().split()[0].strip('#'))

def create_chunk(
    lines: List[str], 
    start_idx: int, 
    end_idx: int, 
    heading_level: int, 
    title: str,
    chunk_id: int
) -> Optional[Dict]:
    """创建文本块
    
    Args:
        lines: 所有文本行
        start_idx: 起始行索引
        end_idx: 结束行索引
        heading_level: 标题层级
        title: 块标题
        chunk_id: 块ID
        
    Returns:
        Dict: 包含块信息的字典,或None(如果块为空)
    """
    if end_idx > start_idx:
        return {
            "chunk_id": chunk_id,
            "level": heading_level,
            "title": title,
            "text": '\n'.join(lines[start_idx:end_idx])
        }
    return None

def optimize_chunks(chunks: List[Dict], min_chunk_size: int = 200) -> List[Dict]:
    """优化文本块,合并过小的块
    
    Args:
        chunks: 原始文本块列表
        min_chunk_size: 最小块大小(字符数)
        
    Returns:
        List[Dict]: 优化后的文本块列表
    """
    optimized = []
    current_chunk = None
    
    for chunk in chunks:
        if current_chunk is None:
            current_chunk = chunk
            continue
            
        # 如果当前块太小,尝试与下一个块合并
        if len(current_chunk["text"]) < min_chunk_size:
            # 只合并相同层级或更低层级的块
            if chunk["level"] >= current_chunk["level"]:
                current_chunk["text"] += "\n" + chunk["text"]
                continue
                
        optimized.append(current_chunk)
        current_chunk = chunk
        
    if current_chunk:
        optimized.append(current_chunk)
        
    return optimized
